<template>
  <div class="login-page">
    <!-- 登陆表单 -->
    <el-form
      :model="loginForm"
      :rules="rules"
      :size="'medium'"
      status-icon
      ref="ruleForm"
      class="my-login-form"
    >
      <!-- logo -->
      <el-row type="flex" class="login-logo" justify="center">
        <img src="../assets/images/jvchat.png" alt srcset />
        <span>聚聊客服</span>
      </el-row>
      <!-- type -->
      <el-row type="flex" class="client-server" justify="center">
        <el-radio-group v-model="clientOrServer" size="medium" @change="clientOrServer = 'client'">
          <el-radio-button label="client">客户端登陆</el-radio-button>
          <el-radio-button label="server">
            <span @click="link2manager">管理端登陆</span>
          </el-radio-button>
        </el-radio-group>
      </el-row>
      <!-- 用户名 -->
      <el-form-item prop="name">
        <el-input
          v-model="loginForm.name"
          size="medium"
          :maxlength="'20'"
          placeholder="输入用户名"
          prefix-icon="el-icon-user"
          @input="changeName()"
        ></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="pass">
        <el-input
          type="password"
          size="medium"
          v-model="loginForm.pass"
          autocomplete="off"
          show-password
          placeholder="输入密码"
          :maxlength="20"
          prefix-icon="el-icon-unlock"
        ></el-input>
      </el-form-item>
      <!-- 记住密码 && 本地调试 -->
      <el-row type="flex" justify="space-around">
        <el-checkbox v-model="rememberPwd">记住密码</el-checkbox>
        <el-checkbox v-model="modifyWebsockUrl">修改ws地址</el-checkbox>
      </el-row>
      <!-- ws输入框 -->
      <el-input size="medium" v-if="modifyWebsockUrl" placeholder="请输入内容" v-model="newWebsockUrl">
        <template slot="prepend">ws://</template>
      </el-input>
      <el-input size="medium" v-else style="visibility: hidden;">
        <template slot="prepend">ws://</template>
      </el-input>
      <!-- 登录 -->
      <el-form-item class="login_btn_box">
        <el-button
          type="primary"
          size="medium"
          :loading="loading"
          :disabled="loading"
          class="login-btn"
          @click="submitForm('ruleForm')"
        >登录</el-button>
      </el-form-item>
      <!-- version -->
      <span class="login-logo-version">v-{{version}}</span>
    </el-form>
    <!-- electron 关闭按钮 -->
    <div style="-webkit-app-region: drag" v-if="currentMode === 'electron'" class="close-title">
      <el-button
        style="-webkit-app-region: no-drag"
        class="el-icon-close"
        size="mini"
        type="text"
        @click="closeElectron"
      ></el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
// import StarBg from '@/components/StarBg.vue'

export default {
  name: 'LoginPage',
  data() {
    let checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      } else {
        callback();
      }
    };
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      rememberPwd: false,
      modifyWebsockUrl: false,
      version: require('../../package.json').version,
      clientOrServer: "client",
      newWebsockUrl: '',
      loginForm: {
        name: '',
        pass: ''
      },
      rules: {
        name: [
          { validator: checkName, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    };
  },
  components: {
    // StarBg
  },
  computed: {
    ...mapGetters({
      currentMode: 'currentMode',
      loading: 'websocket/loginLoading',
    }),
    localName() {
      if (localStorage.getItem('localNameOfJuboChat')) {
        return localStorage.getItem('localNameOfJuboChat')
      }
      return ''
    },
    localPwd() {
      if (localStorage.getItem('localPwdOfJuboChat')) {
        return localStorage.getItem('localPwdOfJuboChat')
      }
      return ''
    }
  },
  methods: {
    // 如果改变用户名 清空密码
    changeName() {
      this.loginForm.pass = ''
    },
    // 登陆
    submitForm(formName) {
      // 如果修改ws
      if (this.modifyWebsockUrl) {
        // 如果有ws地址 就修改
        if (this.newWebsockUrl) {
          localStorage.setItem('localWSOfJuboChat', this.newWebsockUrl)
          this.$store.commit('websocket/SET_WEBSOCKET_URL', 'ws://' + this.newWebsockUrl)
        } else {
          // 如果没有填写ws 提示并返回
          this.$message.warning('请输入ws地址')
          return
        }
      } else {
        this.$store.commit('websocket/SET_WEBSOCKET_URL', 'ws://47.108.193.26:13088')
        //  this.$store.commit('websocket/SET_WEBSOCKET_URL', 'ws://localhost:13088')
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 表单验证通过，可以登陆
          // 记住密码
          if (this.rememberPwd) {
            localStorage.setItem('localNameOfJuboChat', this.loginForm.name)
            localStorage.setItem('localPwdOfJuboChat', this.loginForm.pass)
          }
          // 保存登陆的信息
          this.$store.commit('SET_LOGIN_INFO', { name: this.loginForm.name, pass: this.loginForm.pass })
          // 显示loading
          this.$store.commit('websocket/SET_LOGIN_LOADING', true)
          // 浏览器支持websocket
          if ("WebSocket" in window) {
            // 创建websocket
            this.$store.dispatch('websocket/createWebSocket')
            setTimeout(() => {
              // 登陆
              this.$store.dispatch('websocket/DeviceAuthReq')
            }, 500);
          } else {
            //  如果浏览器不支持WebSocket
            this.$message({
              message: '您的浏览器不支持 WebSocket!，请更换浏览器！',
              type: 'error'
            });
          }

          // 5秒后自动隐藏loading
          setTimeout(() => {
            if (this.loading) {
              this.$store.commit('websocket/SET_LOGIN_LOADING', false)
              this.$message({
                message: '无法连接到服务器！',
                type: 'error',
              })
            }
          }, 3000);
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 退出electron
    closeElectron() {
      this.$ipcRenderer.send('operations', 'exit')
    },
    // 跳转到管理端
    link2manager() {
      let url = 'http://47.108.193.26/'
      if (this.currentMode === 'electron') {
        const { shell } = window.require('electron')
        shell.openExternal(url)
      } else {
        var a = document.createElement('a');
        a.setAttribute('href', url);
        a.setAttribute('target', '_blank');
        a.setAttribute('id', 'js_a');
        //防止反复添加
        if (document.getElementById('js_a')) {
          document.body.removeChild(document.getElementById('js_a'));
        }
        document.body.appendChild(a);
        a.click();
      }
    }
  },
  watch: {
    rememberPwd(val) {
      if (val) {
        localStorage.setItem('remarkPwdOfJuboChat', 1)
      } else {
        localStorage.removeItem('remarkPwdOfJuboChat')
        localStorage.removeItem('localNameOfJuboChat')
        localStorage.removeItem('localPwdOfJuboChat')
      }
    },
    modifyWebsockUrl(val) {
      if (val) {
        localStorage.setItem('ModifyWSOfJuboChat', 1)
      } else {
        localStorage.removeItem('ModifyWSOfJuboChat')
      }
    }
  },
  created() {
    // 记住密码
    if (localStorage.getItem('remarkPwdOfJuboChat')) {
      this.rememberPwd = true
      if (this.localName && this.localPwd) {
        this.loginForm.name = this.localName
        this.loginForm.pass = this.localPwd
      }
    }
    // 防抖
    this.changeName = this._.debounce(this.changeName, 300)
  },
  mounted() {
    // 修改ws
    if (localStorage.getItem('ModifyWSOfJuboChat')) {
      if (localStorage.getItem('localWSOfJuboChat')) {
        this.newWebsockUrl = localStorage.getItem('localWSOfJuboChat')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  width: 100%;
  height: 100%;
  background: no-repeat;
  //   background-image: url(~@/../public/images/kdd_big_bg.png);
  background-image: url(~@/assets/images/kdd_big_bg.png);
  background-size: cover;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.my-login-form {
  float: right;
  width: 400px;
  height: 400px;
  margin-right: 10%;
  background: #fff;
  padding: 10px 50px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .client-server,
  .login-logo {
    margin-bottom: 10px;
  }
  .login-logo {
    display: flex;
    align-items: center;
    img {
      width: 50px;
      height: 50px;
    }
    span {
      margin-left: 20px;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .login_btn_box {
    margin-bottom: 0;
    display: flex;
    justify-content: center;
    .login-btn {
      width: 150px;
    }
  }

  .login-logo-version {
    margin-top: 5px;
    color: $font-color-2;
    text-align: center;
  }

  ::v-deep .el-input-group__prepend {
    padding: 0 10px;
  }
}

.close-title {
  position: absolute;
  top: 0;
  width: 700px;
  height: 30px;
  display: flex;
  justify-content: flex-end;
  border-radius: 5px;
  .el-icon-close {
    font-size: 16px;
    padding: 0;
    margin-right: 10px;
    color: white;
    &:hover {
      color: $danger-color-base;
      font-weight: 600;
    }
  }
}

@media only screen and (max-width: 700px) {
  .login-page {
    border-radius: 5px;
    .my-login-form {
      margin-right: 10px;
      height: 350px;
      width: 350px;
      padding: 5px 20px;
      .client-server,
      .login-logo {
        margin-bottom: 5px;
      }
    }
  }
}
</style>
